from flask_restful import Resource, reqparse
from flask import request
import os
import json
import time
import oss2
from urllib import request as url_request
from http import HTTPStatus
import dashscope

# =================== 配置 ===================
UPLOAD_FOLDER = "/tmp"
OSS_ENDPOINT = 'https://oss-rg-china-mainland.aliyuncs.com'
OSS_ACCESS_KEY_ID = 'LTAI5tRBMw7FB6RHMUMnroPN'
OSS_ACCESS_KEY_SECRET = '2IbLCayXskvJhiit8bzg3vL0ZXkzMp'
OSS_BUCKET_NAME = 'fujg-bucket'
OSS_OBJECT_NAME = '001/temp.mp3'
DASHSCOPE_API_KEY = "sk-434b6f278d13400691e31cb1e34aca1e"

# =================== 工具函数 ===================

def init_dashscope_api_key():
    dashscope.api_key = DASHSCOPE_API_KEY

def push_file_to_oss(local_file_path):
    """将本地文件上传到 OSS"""
    auth = oss2.Auth(OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET)
    bucket = oss2.Bucket(auth, OSS_ENDPOINT, OSS_BUCKET_NAME)
    result = bucket.put_object_from_file(OSS_OBJECT_NAME, local_file_path)
    print(f"[OSS] 文件已上传：{OSS_OBJECT_NAME}")
    return result.status == 200

def speech_to_text():
    """使用阿里云 DashScope 转写 OSS 文件"""
    task_response = dashscope.audio.asr.Transcription.async_call(
        model='paraformer-v2',
        file_urls=[f'https://{OSS_BUCKET_NAME}.{OSS_ENDPOINT.split("//")[1]}/{OSS_OBJECT_NAME}'],
        language_hints=['zh', 'en']
    )

    transcription_response = dashscope.audio.asr.Transcription.wait(task=task_response.output.task_id)

    if transcription_response.status_code != HTTPStatus.OK:
        raise RuntimeError(f"Transcription failed: {transcription_response.output.message}")

    results = []
    for item in transcription_response.output['results']:
        url = item['transcription_url']
        text = json.loads(url_request.urlopen(url).read().decode('utf8'))['transcripts'][0]['text']
        results.append(text)
    return results

# =================== Flask 接口 ===================

class ConsoleAliyunRequestApi(Resource):
    def get(self):
        return {"test": "hello world"}

    def post(self):
        if 'file' not in request.files:
            return {"error": "Missing 'file' in request"}, 400
        file = request.files['file']
        if file.filename == '':
            return {"error": "Empty filename"}, 400

        # 保存上传文件
        save_path = os.path.join(UPLOAD_FOLDER, file.filename)
        if os.path.exists(save_path):
            os.remove(save_path)
        file.save(save_path)
        print(f"[UPLOAD] 保存路径: {save_path}")

        try:
            # 上传至 OSS
            push_file_to_oss(save_path)

            # 调用语音转文字
            init_dashscope_api_key()
            result = speech_to_text()
            print(f"[DASHSCOPE] 转写结果: {result}")
            return {"text": result}
        except Exception as e:
            print(f"[ERROR] {e}")
            return {"error": str(e)}, 500

# 注册到 API
from controllers.console import api
api.add_resource(ConsoleAliyunRequestApi, "/wav2text")
